<template>
  <div class="login-container">
    <!-- 动态背景 -->
    <dynamic-background type="login" :overlay-opacity="0.8" />
    
    <transition name="fade-in" appear>
      <div class="login-box">
        <!-- 装饰图案 -->
        <div class="decoration-circles">
          <div class="circle circle-1"></div>
          <div class="circle circle-2"></div>
          <div class="circle circle-3"></div>
        </div>
        <div class="decoration-dots">
          <div class="dot-group dot-group-1"></div>
          <div class="dot-group dot-group-2"></div>
        </div>
        
        <div class="login-left">
          <div class="logo-header">
            <img src="../images/logo-圆角.png" alt="small-logo" class="small-logo" />
            <span class="logo-text">云栈智慧管家</span>
          </div>
          <div class="animation-container">
            <login-animation />
          </div>
          <p class="slogan-text">让我们一起开启新零售时代</p>
        </div>
        <div class="login-right">
          <div class="welcome-text">
            <h2>👋 欢迎回来！</h2>
          </div>
          <el-form ref="form" :model="form" :rules="rules" class="login-form">
            <el-form-item prop="username">
              <el-input 
                v-model="form.username" 
                placeholder="请输入用户名/邮箱"
                prefix-icon="el-icon-user">
              </el-input>
        </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="form.password" 
                type="password" 
                placeholder="请输入密码"
                prefix-icon="el-icon-lock">
              </el-input>
        </el-form-item>
            <el-form-item prop="validCode">
              <div class="valid-code-container">
                <el-input 
                  v-model="form.validCode" 
                  placeholder="请输入验证码" 
                  class="valid-code-input"
                  prefix-icon="el-icon-key">
                </el-input>
                <valid-code :value.sync="correctCode" class="valid-code-img" ref="validCode"></valid-code>
              </div>
        </el-form-item>
            <el-button type="primary" class="login-button" :disabled="!form.agreement" @click="handleSubmit">登录</el-button>
            <div class="agreement-register-container">
              <div class="agreement-container">
                <el-checkbox v-model="form.agreement">
                  接受<el-button type="text" class="agreement-btn" @click.native.prevent="showAgreementDialog">用户协议</el-button>
                </el-checkbox>
              </div>
              <div class="register-forget-container">
                <el-button type="text" class="forget-btn" @click="goToForget">忘记密码</el-button>
                <el-button type="text" class="register-btn" @click="goToRegister">立即注册</el-button>
              </div>
            </div>
      </el-form>
        </div>
      </div>
    </transition>
    
    <!-- 用户协议对话框 -->
    <el-dialog
      title="用户协议"
      :visible.sync="agreementDialogVisible"
      width="50%"
      custom-class="agreement-dialog"
      center>
      <div class="agreement-content" style="font-family: 'Microsoft YaHei', sans-serif; color: #333; line-height: 1.6; max-width: 800px; margin: 0 auto;">
  <h2 style="font-size: 20px; font-weight: bold; color: #2c3e50; border-bottom: 2px solid #eee; padding-bottom: 8px; margin-bottom: 15px;">
    云栈智慧管家用户协议
    <span style="font-size: 14px; color: #95a5a6; margin-left: 10px;">（版本号：1.0 | 生效日期：2025年4月12日）</span>
  </h2>

  <!-- 一、引言 -->
  <div style="margin-bottom: 25px;">
    <h3 style="font-size: 18px; font-weight: bold; color: #34495e; margin-bottom: 10px;">一、引言</h3>
    <p style="margin-bottom: 15px; text-indent: 2em;">欢迎使用"云栈智慧管家"便利店管理系统（以下简称"本系统"）。本协议是用户与开发者之间的法律协议，规范您对本系统的访问与使用。<strong style="color: #e74c3c;">请仔细阅读并同意全部条款后再进行注册或使用。</strong></p>
  </div>

  <!-- 二、用户注册与账户管理 -->
  <div style="margin-bottom: 25px;">
    <h3 style="font-size: 18px; font-weight: bold; color: #34495e; margin-bottom: 15px;">二、用户注册与账户管理</h3>
    
    <div style="margin-left: 20px; margin-bottom: 15px;">
      <h4 style="font-weight: 600; color: #16a085; margin-bottom: 8px;">1. 注册条件</h4>
      <p style="margin-bottom: 8px;">▪ 用户需年满16周岁，提供真实、准确、完整的注册信息（包括账号、密码、邮箱等）。</p>
      <p style="margin-bottom: 8px;">▪ 注册需通过图形验证码验证。</p>
    </div>

    <div style="margin-left: 20px; margin-bottom: 15px;">
      <h4 style="font-weight: 600; color: #16a085; margin-bottom: 8px;">2. 账户安全</h4>
      <p style="margin-bottom: 8px;">▪ 用户密码经加密存储，<span style="color: #c0392b;">禁止转让、出借账户</span>。因用户保管不善导致的损失由用户自行承担。</p>
      <p style="margin-bottom: 8px;">▪ 管理员有权根据系统规则添加、修改或删除用户信息，操作需符合隐私保护及安全规范。</p>
    </div>

    <div style="margin-left: 20px;">
      <h4 style="font-weight: 600; color: #16a085; margin-bottom: 8px;">3. 密码找回</h4>
      <p>▪ 用户可通过绑定邮箱验证重置密码，系统将发送安全链接至已验证的联络方式。</p>
    </div>
  </div>

  <!-- 三、服务功能说明 -->
  <div style="margin-bottom: 25px;">
    <h3 style="font-size: 18px; font-weight: bold; color: #34495e; margin-bottom: 15px;">三、服务功能说明</h3>
    <div style="margin-left: 20px;">
      <p style="margin-bottom: 10px;">▪ <strong>商品管理：</strong>管理员可录入、修改商品信息，需确保数据准确性。系统提供查询功能，<em style="color: #7f8c8d;">数据错误导致的经营风险由操作者承担</em>。</p>
      <p style="margin-bottom: 10px;">▪ <strong>销售记录：</strong>系统自动记录交易详情，<span style="color: #c0392b;">禁止篡改、删除交易记录</span>，违规将导致账户冻结。</p>
      <p style="margin-bottom: 10px;">▪ <strong>库存监控：</strong>实时显示库存状态，<span style="background-color: #fcf8e3; padding: 2px 4px;">系统不保证预警及时性</span>，补货责任由操作者承担。</p>
    </div>
  </div>

  <!-- 四、隐私与数据保护 -->
  <div style="margin-bottom: 25px;">
    <h3 style="font-size: 18px; font-weight: bold; color: #34495e; margin-bottom: 15px;">四、隐私与数据保护</h3>
    <div style="margin-left: 20px;">
      <p style="margin-bottom: 8px;">▪ <strong>收集范围：</strong>账号、密码、操作记录等使用数据</p>
      <p style="margin-bottom: 8px;">▪ <strong>使用规则：</strong><span style="color: #27ae60;">未经同意不得向第三方提供数据</span>，法律要求除外</p>
    </div>
  </div>

  <!-- 五、免责声明 -->
  <div style="margin-bottom: 25px;">
    <h3 style="font-size: 18px; font-weight: bold; color: #34495e; margin-bottom: 15px;">五、免责声明</h3>
    <div style="margin-left: 20px; background-color: #f9f9f9; padding: 15px; border-radius: 4px;">
      <p style="margin-bottom: 8px;">因以下情形导致的损失不承担责任：</p>
      <p style="margin-bottom: 8px;">- 不可抗力（自然灾害、网络攻击）</p>
      <p style="margin-bottom: 8px;">- 用户操作失误</p>
      <p style="margin-bottom: 8px;">- 第三方服务故障</p>
      <p style="margin-bottom: 8px;">注意：本协议所有解释权归开发者所有。</p>
    </div>
  </div>

  <!-- 协议底部 -->
  <div style="border-top: 1px solid #eee; padding-top: 15px; margin-top: 20px;">
    <p style="font-size: 14px; color: #95a5a6; text-align: center;">
      注册或使用即视为已阅读并同意本协议全部内容<br>
      联系方式：<a href="yt_90106@163.com" style="color: #3498db;">yt_90106@163.com</a>
    </p>
  </div>
</div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="agreementDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="acceptAgreement">同意</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { login } from '@/api/user'
import ValidCode from '@/components/ValidCode.vue'
import DynamicBackground from '@/components/DynamicBackground.vue'
import LoginAnimation from '@/components/LoginAnimation.vue'

export default {
  name: 'LoginView',
  components: {
    ValidCode,
    DynamicBackground,
    LoginAnimation
  },
  data() {
    // 验证码校验规则
    const validateValidCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'))
      } else if (value.toLowerCase() !== this.correctCode.toLowerCase()) {
        // 验证码错误时自动刷新
        this.$nextTick(() => {
          this.$refs.validCode.draw()
        })
        callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }
    
    return {
      form: {
        username: '',
        password: '',
        validCode: '',
        agreement: false
      },
      agreementDialogVisible: false,
      correctCode: '', // 正确的验证码
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        validCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: validateValidCode, trigger: 'blur' }
        ],
        agreement: [
          { 
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请接受用户协议'))
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ]
      }
    };
  },
  methods: {
    async handleSubmit() {
      try {
        // 添加表单验证
        const valid = await this.$refs.form.validate().catch(() => false)
        if (!valid) {
          // 如果是验证码错误，自动刷新验证码
          if (this.form.validCode && this.form.validCode.toLowerCase() !== this.correctCode.toLowerCase()) {
            this.$refs.validCode.draw() // 刷新验证码
          }
          return false
        }
        
        const res = await login(this.form)
        
        // 检查后端返回的 code 字段
        if (res.code !== 200) {
          // 错误消息已经在request.js中处理，这里只需要刷新验证码并清空输入
          this.$refs.validCode.draw()
          this.form.password = ''
          this.form.validCode = ''
          return
        }

        if (res.data) {
          // 确保返回数据中包含必要的信息
          if (!res.data.token || !res.data.userInfo) {
            this.$message.error('登录失败：返回数据格式错误')
            return
          }

          // 保存token和用户信息
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
          
          // 显示登录成功提示
          this.$message.success(res.message || '登录成功')
          
          // 跳转到首页
          this.$router.push('/dashboard')
        }
      } catch (error) {
        console.error('登录失败:', error)
        
        // 刷新验证码并清空输入
        this.$refs.validCode.draw()
        this.form.password = ''
        this.form.validCode = ''
      }
    },
    goToRegister() {
      // 添加页面离开动画
      document.querySelector('.login-box').classList.add('slide-out-left')
      
      // 延迟导航以等待动画完成
      setTimeout(() => {
        this.$router.push('/user/register')
      }, 500)
    },
    goToForget() {
      // 添加页面离开动画
      document.querySelector('.login-box').classList.add('slide-out-left')
      
      // 延迟导航以等待动画完成
      setTimeout(() => {
        this.$router.push('/user/forget')
      }, 500)
    },
    showAgreementDialog() {
      this.agreementDialogVisible = true;
    },
    acceptAgreement() {
      this.form.agreement = true;
      this.agreementDialogVisible = false;
    }
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  /* 移除旧的背景图 */
  /* background: url('../images/background.png') center center / cover no-repeat; */
  position: relative;
  overflow: hidden;
}

/* 添加进入动画 */
.fade-in-enter-active {
  transition: all 0.8s ease;
}

.fade-in-enter {
  opacity: 0;
  transform: translateY(20px);
}

/* 添加页面切换动画 */
.slide-out-left {
  animation: slideOutLeft 0.5s forwards;
}

@keyframes slideOutLeft {
  from {
    transform: translateX(0);
    opacity: 1;
  }
  to {
    transform: translateX(-50px);
    opacity: 0;
  }
}

.login-box {
  width: 900px;
  height: 500px;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
  display: flex;
  overflow: hidden;
  position: relative;
  z-index: 1;
  /* 添加玻璃效果 */
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.85);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* 装饰图案样式 */
.decoration-circles {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
  z-index: 0;
}

.circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
}

.circle-1 {
  width: 300px;
  height: 300px;
  background: linear-gradient(135deg, #ff6b00, #ff8533);
  top: -150px;
  right: -50px;
}

.circle-2 {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, #ff8533, #ffa066);
  bottom: -100px;
  right: 250px;
}

.circle-3 {
  width: 150px;
  height: 150px;
  background: linear-gradient(135deg, #ffa066, #ffbb99);
  top: 50px;
  right: 300px;
  opacity: 0.07;
}

.decoration-dots {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

.dot-group {
  position: absolute;
  background-image: radial-gradient(circle, #ff6b00 1px, transparent 2px);
  background-size: 18px 18px;
  opacity: 0.15;
}

.dot-group-1 {
  width: 200px;
  height: 200px;
  top: 20px;
  right: 40px;
  transform: rotate(15deg);
}

.dot-group-2 {
  width: 150px;
  height: 150px;
  bottom: 30px;
  right: 180px;
  transform: rotate(-10deg);
  background-size: 12px 12px;
}

/* 增强左侧面板样式 */
.login-left {
  width: 40%;
  background: linear-gradient(135deg, #304156 0%, #263445 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px;
  position: relative;
  box-shadow: 5px 0 15px rgba(0, 0, 0, 0.1);
  
  .animation-container {
    width: 100%;
    height: 240px;
    margin: 10px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: visible;
  }
}

.logo-header {
  position: absolute;
  top: 20px;
  left: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.small-logo {
  width: 30px;
  height: 30px;
  object-fit: contain;
}

.logo-text {
  color: #fff;
  font-size: 16px;
  white-space: nowrap;
}

.slogan-text {
  color: #fff;
  font-size: 16px;
  margin-top: 20px;
  text-align: center;
}

.login-right {
  width: 60%;
  padding: 40px 60px;
}

.welcome-text {
  margin-bottom: 30px;
  text-align: left;
}

.welcome-text h2 {
  font-size: 28px;
  color: #304156;
  margin-bottom: 10px;
}

.login-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 30px;
}

.el-input /deep/ .el-input__inner {
  height: 50px;
  border-radius: 25px;
  padding-left: 45px;
  border-color: #dcdfe6;
}

.el-input /deep/ .el-input__inner:hover {
  border-color: #ff6b00;
}

.el-input /deep/ .el-input__inner:focus {
  border-color: #ff6b00;
}

.el-input /deep/ .el-input__prefix {
  left: 20px;
}

.login-button {
  width: 100%;
  height: 50px;
  border-radius: 25px;
  background: #ff6b00;
  border-color: #ff6b00;
  font-size: 16px;
  margin-bottom: 15px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.login-button:hover,
.login-button:focus {
  background: #ff8533;
  border-color: #ff8533;
  color: #fff;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 107, 0, 0.3);
}

.login-button:active {
  background: #e65d00;
  border-color: #e65d00;
  color: #fff;
  transform: translateY(0);
}

.agreement-register-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.agreement-container {
  text-align: left;
}

.register-container {
  text-align: right;
}

.forget-btn {
  color: #364360;
  font-size: 14px;
}

.forget-btn:hover,
.forget-btn:focus {
  color: #2d384f;
  text-decoration: none;
  background: transparent;
}

.forget-btn:active {
  color: #21293b;
  text-decoration: none;
  background: transparent;
}

.register-btn {
  color: #ff6b00;
  font-size: 14px;
}

.register-btn:hover,
.register-btn:focus {
  color: #ff8533;
  text-decoration: none;
  background: transparent;
}

.register-btn:active {
  color: #e65d00;
  text-decoration: none;
  background: transparent;
}

.valid-code-container {
  display: flex;
  align-items: center;
}

.valid-code-input {
  flex: 1;
  margin-right: 10px;
}

.valid-code-img {
  cursor: pointer;
}

.agreement-btn {
  padding: 0;
  font-size: 14px;
  color: #ff6b00;
  margin-left: 4px;
}

.agreement-btn:hover,
.agreement-btn:focus {
  color: #ff8533;
}

.agreement-dialog .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.agreement-dialog .el-dialog__body {
  padding: 30px 20px;
  max-height: 400px;
  overflow-y: auto;
}

.agreement-dialog .el-dialog__footer {
  padding: 10px 20px 20px;
  text-align: right;
}

.agreement-dialog .el-button--primary {
  background-color: #ff6b00;
  border-color: #ff6b00;
}

.agreement-dialog .el-button--primary:hover,
.agreement-dialog .el-button--primary:focus {
  background-color: #ff8533;
  border-color: #ff8533;
}

.agreement-content {
  line-height: 1.6;
  color: #606266;
}
</style> 